﻿using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using Syufy.BINLookup.Web.Helpers;
using Syufy.BINLookup.Web.Models;

namespace Syufy.BINLookup.Web.Controllers
{
    /// <summary>
    /// MVC page for BIN lookup.
    /// </summary>
    public class BinLookupController : Controller
    {
        // GET: BinLookup
        /// <summary>
        /// Landing page for BIN lookup.
        /// </summary>
        /// <returns>View.</returns>
        public ActionResult Index()
        {
            return View();
        }

        // POST: BinLookup
        /// <summary>
        /// Postback method for search/save from UI.
        /// </summary>
        /// <param name="BinNumber">BIN number.</param>
        /// <param name="AccountNumber">Account number.</param>
        /// <param name="Override">Override feature.</param>
        /// <param name="CardType">Card type.</param>
        /// <returns>BIN data.</returns>
        [HttpPost]
        public async Task<ActionResult> Index(string BinNumber, string AccountNumber, bool Override = false, string CardType = "")
        {
            // Set ViewBag values
            ViewBag.PersistError = false;
            ViewBag.Override = Override;

            var search = new RestClient<cardBINDB>(Request.Url.GetLeftPart(UriPartial.Authority));
            var model = await search.GetRequest(string.Concat("/api/BinData/", BinNumber));

            if (model != null || Override)
            {
                // Save record in database
                var history = new RestClient<BINLookupHistory>(Request.Url.GetLeftPart(UriPartial.Authority));
                var insert = new BINLookupHistory()
                {
                    CardBIN = BinNumber,
                    AccountNumber = AccountNumber,
                    CardType = Override ? CardType : model.cardType,
                    Override = Override,
                    CreatedBy = User.Identity.Name,
                    CreatedDate = DateTime.Now,
                    LastModifiedBy = User.Identity.Name,
                    LastModifiedDate = DateTime.Now,
                };

                var result = await history.PostRequest("/api/BinData/", insert);
                if (result.ID == 0)
                {
                    ViewBag.PersistError = true;
                }
            }

            return View(model);
        }
    }
}
